import store from '@/store'
import cfg from "@/config"
import { Router, RouteRecordRaw } from 'vue-router'
const { routesWhiteList, recordRoute } = cfg
const BeforeResolve = (router: Router) => {
  router.beforeResolve(async (to, from, next) => {
    /** 获取状态中的token */
    let hasToken = store.getters['user/accessToken']
    if (hasToken) {
      /** 是否跳转login页 */
      if (to.name === "login") {
        next('/')
      }
      else {
        /** 是否有权限 */
        const hasPermissions = store.getters['user/permissions'] && store.getters['user/permissions'].length > 0
        if (hasPermissions) {
          next()
        }
        else {
          try {
            /** 请求接口 获取权限  */
            const permissions = await store.dispatch('user/getUserInfo')
            if (!permissions) {
              await store.dispatch('user/resetAccessToken')
              next("/login")
            }
            /** 根据权限获取动态路由 */
            const accessRoutes: RouteRecordRaw[] = await store.dispatch('routes/setRoutes', permissions)
            console.log(accessRoutes)
            accessRoutes.forEach((route: RouteRecordRaw) => {
              router.addRoute(route)
            });
            console.log(router)
            next({ ...to })
          } catch (err) {
            await store.dispatch('user/resetAccessToken')
            console.log(err)
            if (recordRoute) {
              next(`/login?redirect=${to.path}`)
            } else {
              next('/login')
            }
          }
        }
      }
    }
    else {
      /** 查看是否需要token验证的路由 */
      if (routesWhiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        /** 判断是否需要记录当前页面path跳转login */
        if (recordRoute) {
          next(`/login?redirect=${to.path}`)
        } else {
          next('/login')
        }
      }
    }
  })
}
export default BeforeResolve



